package com.guanyou;

import com.guanyou.lock.IDLock;
import com.guanyou.lock.RedisLock;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Component
public class BookRedisBean {

    @Autowired
    BookJedisConfig bookJedisConfig;

    @Autowired
    JedisConfig jedisConfig;

    public JedisPool getJedisPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMinIdle(jedisConfig.getMinIdle());
        config.setMaxIdle(jedisConfig.getMaxIdle());
        config.setMaxTotal(jedisConfig.getMaxTotal());
        config.setTestOnBorrow(jedisConfig.isTestOnBorrow());
        config.setTestOnReturn(jedisConfig.isTestOnReturn());
        config.setMaxWaitMillis(jedisConfig.getMaxWaitMillis());
        config.setTestWhileIdle(jedisConfig.isTestWhileIdle());

        return new JedisPool(config,
                bookJedisConfig.getHost(),
                bookJedisConfig.getPort(),
                bookJedisConfig.getTimeout(),
                StringUtils.isEmpty(bookJedisConfig.getPassword()) ? null : bookJedisConfig.getPassword(),
                bookJedisConfig.getDatabase());

    }

    @Bean("bookRedisUtil")
    public RedisUtil getBookRedisUtil() {
        return new RedisUtil(this.getJedisPool());
    }

    @Autowired
    private RedisUtil bookRedisUtil;

    @Bean
    public IDLock getIdLock() {
        return new RedisLock(bookRedisUtil, "lock.account");
    }

}
